import { ElMessage } from 'element-plus'
import {
  COMPANY_PRODUCT_LIST,
  CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT,
  DETAILED_LIST_OF_COMPANY_INDICATORS,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE,
  ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE,
  TABLE_FIELD_QUARTER,
  TABLE_FIELD_YEAR,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
} from '../config'
import type ReportPerson from '../ReportPerson.vue'
import type { EnergyDataReportList, ReportColumnsItem } from '../types'
import {
  saveOrUpdateCompanyIndicatorDetails,
  saveOrUpdateCompanyProduct,
  saveOrUpdateEnergyConsumptionStructure,
  saveOrUpdateEnergyConsumptionStructureSchedule,
  saveOrUpdateEquipmentStatus,
  saveOrUpdateGoalCompletionStatus,
  saveOrUpdateProductEnergyConsumption,
  saveOrUpdateReconstructionProject,
  saveOrUpdateUnitDetails,
} from '@/api/modules/enterpriseQuarterlyReport'
import type {
  IntervalHandle,
} from '@/components/EnergyDataReport/types'
import {
  StatementStatus,
} from '@/components/EnergyDataReport/types'

function useStatementSave(option: {
  statementId: ComputedRef<number>
  year: ComputedRef<number | string>
  quarter: ComputedRef<number | string>
  enterpriseId: ComputedRef<number | string>
  reportPersonRef: Ref<InstanceType<typeof ReportPerson> | null>
  getData?: () => any
  flattenColumns?: ComputedRef<Omit<ReportColumnsItem, 'children'>[]>
  lists?: Ref<
    EnergyDataReportList<{
      key: string
      value: string | number
      editable?: boolean
      [propName: string]: any
    }>[]
  >
  getCalc?: (row: number, prop: string, value?: string | number) => any
  description?: Ref<{
    key: string
    value: string | number
    editable?: boolean
  }>
  summary?: Ref<{ uuid: string, data: any[] }>
  currentValue?: Ref<string | number>
  previousValue?: Ref<string | number>
}) {
  const {
    statementId,
    getData: _getData,
    year,
    quarter,
    flattenColumns,
    reportPersonRef,
    lists,
    getCalc,
    enterpriseId,
    description: _description,
    summary,
    currentValue,
    previousValue,
  } = toValue(option)

  const save = computed(() => {
    const tableAccountId = Number(statementId.value)
    let method = null
    switch (tableAccountId) {
      case PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID:
        method = saveOrUpdateGoalCompletionStatus
        break
      case TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID:
        method = saveOrUpdateProductEnergyConsumption
        break
      case CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT.ID:
        method = saveOrUpdateEquipmentStatus
        break
      case ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID:
        method = saveOrUpdateReconstructionProject
        break
      case ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID:
        method = saveOrUpdateEnergyConsumptionStructure
        break
      case COMPANY_PRODUCT_LIST.ID:
        method = saveOrUpdateCompanyProduct
        break
      case DETAILED_LIST_OF_COMPANY_INDICATORS.ID:
        method = saveOrUpdateCompanyIndicatorDetails
        break
      case ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID:
        method = saveOrUpdateEnergyConsumptionStructureSchedule
        break
      case ENTERPRISE_BASIC_INFORMATION_TABLE_ID:
        method = saveOrUpdateUnitDetails
        break
    }
    return method
  })

  const getData = () => {
    if (_getData) {
      return _getData()
    }
    const props = flattenColumns?.value.map(v => v.prop as string)
    const isNotEmpty = (array: EnergyDataReportList['data']): boolean =>
      array.some((v) => {
        return v.value !== '' && v.value != null
      })

    const listsData = lists?.value.map(v => v.data)
    const listsValue = listsData?.filter(v => isNotEmpty(v))
    return listsValue?.map((v, i) => {
      const obj = {} as any
      props?.forEach((prop, index) => {
        obj[prop]
          = typeof getCalc === 'function'
            ? String(getCalc(i, prop, (v[index] as any).value) || '')
            : v[index]?.value || ''
      })
      obj[TABLE_FIELD_YEAR] = String(year.value)
      obj[TABLE_FIELD_QUARTER] = String(quarter.value)
      return obj
    })
  }
  const saveOrUpdate = (
    state: StatementStatus,
    illustrate = '',
    callback?: (res: any) => any,
  ) => {
    const data = getData()
    const informer = reportPersonRef.value?.getData?.()
    const params: any = {
      [TABLE_FIELD_YEAR]: String(year.value),
      [TABLE_FIELD_QUARTER]: String(quarter.value),
      tenantId: enterpriseId.value,
      ...informer,
    }
    const tId = statementId.value
    if (tId === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
      // 企业情况表
      params.data = data.data
      params.list = data.list

      params.data = {
        ...params.data,
        state,
        illustrate,
      }
    }
    else {
      params.list = (data || []).map((v: any) => ({
        ...v,
        state,
        illustrate,
      }))
    }

    if (tId === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID) {
      // 进度节能目标完成情况表
      // 进度节能量目标完成情况说明
      const description = _description?.value
      params.list.push({
        [TABLE_FIELD_YEAR]: String(year.value),
        [TABLE_FIELD_QUARTER]: String(quarter.value),
        projectName: '进度节能量目标完成情况说明',
        oneYear: description?.value || '',
        state,
        illustrate,
      })
    }

    if (
      [
        ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID,
        ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID,
      ].includes(tId)
    ) {
      // 能源结构表和附表
      const item = data[0] || {}
      if (summary) {
        params.list.push({
          ...item,
          ...summary?.value?.data.reduce((acc, v) => {
            acc[v.key] = String(v.value || '')
            return acc
          }, {}),
          state,
          illustrate,
        })
      }

      if (tId === ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID) {
        // 本年综合能源消费量（当量值）
        // 上年综合能源消费量（当量值）
        params.consumptionThisYear = currentValue?.value
        params.consumptionLastYear = previousValue?.value
      }
    }

    // console.log('params: ', params)
    if (save.value) {
      return save.value(params).then((res: any) => {
        callback?.(res)
      })
    }
    else {
      return Promise.resolve()
    }
  }

  const report = async () => {
    await saveOrUpdate(StatementStatus.REPORTED)
    ElMessage.success('操作成功')
  }

  const saveStage = async () => {
    await saveOrUpdate(StatementStatus.STAGED)
    ElMessage.success('操作成功')
  }

  // 是否开启自动暂存
  const needAutoSave = false
  let timer: IntervalHandle
  const autoSave = () => {
    saveOrUpdate(StatementStatus.STAGED)
  }

  if (needAutoSave) {
    onBeforeUnmount(() => {
      timer && clearInterval(timer)
    })

    onMounted(() => {
      timer = setInterval(() => {
        autoSave()
      }, 10e3)
    })
    onDeactivated(() => {
      timer && clearInterval(timer)
    })

    onActivated(() => {
      timer = setInterval(() => {
        autoSave()
      }, 10e3)
    })
  }

  return {
    autoSave,
    saveOrUpdate,
    report,
    saveStage,
  }
}

export default useStatementSave
